<template>
  <div class="post-detail">
    <!-- 返回按钮 -->
    <van-nav-bar
      title="帖子详情"
      left-text="返回"
      left-arrow
      @click-left="goBack"
    />

    <!-- 帖子内容区域 -->
    <div class="post-content">
      <!-- 发布者信息 -->
      <div class="user-info">
        <img :src="post.user?.avatar || defaultAvatar" class="user-avatar" alt="用户头像" />
        <div class="user-meta">
          <div class="username">{{ post.user?.username || '未知用户' }}</div>
        </div>
      </div>

      <!-- 帖子标题和内容 -->
      <div class="post-main">
        <h2 class="post-title" v-if="post.title">{{ post.title }}</h2>
        <p class="post-text">{{ post.content }}</p>
      </div>

      <!-- 图片轮播 -->
      <van-swipe
        v-if="postImages.length > 0"
        v-model="currentSwipe"
        :autoplay="3000"
        indicator-color="white"
        indicator-active-color="rgba(255,255,255,0.6)"
      >
        <van-swipe-item v-for="(img, index) in postImages" :key="index">
          <img :src="img" class="swipe-image" alt="帖子图片" @error="handleImageError($event, index)" />
        </van-swipe-item>
      </van-swipe>

      <!-- 元数据信息 -->
      <div class="post-meta">
        <span class="meta-item">{{ formatTime(post.createTime) }}</span>
        <span class="meta-item">{{ post.viewCount }}次浏览</span>
      </div>

      <!-- 互动区域 -->
      <div class="interaction">
        <van-button
          icon="like-o"
          :class="{ 'liked': isLiked }"
          @click="handleLike"
          size="small"
          type="primary"
        >
          {{ post.likeCount }}
        </van-button>
        <van-button
          icon="comment-o"
          @click="showCommentInput = !showCommentInput"
          size="small"
        >
          {{ commentCount }}
        </van-button>
      </div>

      <!-- 评论区域 -->
      <div class="comments">
        <h4>评论 ({{ commentCount }})</h4>
        
        <!-- 评论列表 -->
        <div class="comment-list">
          <div class="comment-item" v-for="(comment, index) in comments" :key="comment.id || index">
            <img :src="comment.user?.avatar || defaultAvatar" class="comment-avatar" alt="评论者头像" />
            <div class="comment-info">
              <div class="comment-header">
                <span class="comment-username">{{ comment.user?.username || '匿名用户' }}</span>
                <span class="comment-time">{{ formatTime(comment.createTime) }}</span>
              </div>
              <p class="comment-content">{{ comment.content }}</p>
              <div class="comment-actions">
                <button class="like-comment" @click="handleCommentLike(comment)">
                  <van-icon name="like-o" :class="{ 'liked': comment.isLiked }" />
                  <span>{{ comment.likeCount || 0 }}</span>
                </button>
                <button class="reply-comment" @click="replyToComment(comment)">回复</button>
              </div>
            </div>
          </div>
          
          <!-- 空评论提示 -->
          <div class="empty-comments" v-if="comments.length === 0">
            暂无评论，快来发表第一条评论吧~
          </div>
        </div>

        <!-- 评论输入框 -->
        <div class="comment-input-container" v-show="showCommentInput">
          <img :src="currentUserAvatar" class="input-avatar" alt="当前用户头像" />
          <input
            type="text"
            v-model="newComment"
            placeholder="写下你的评论..."
            class="comment-input"
            @keyup.enter="addComment"
          />
          <van-button @click="addComment" size="small" type="primary" :disabled="!newComment.trim()">
            发布
          </van-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import api from '@/api'
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useRoute } from 'vue-router'
import { NavBar, Swipe, SwipeItem, Button, Icon } from 'vant'

const router = useRouter()
const route = useRoute()

// 组件注册
const components = {
  VanNavBar: NavBar,
  VanSwipe: Swipe,
  VanSwipeItem: SwipeItem,
  VanButton: Button,
  VanIcon: Icon
}

// 默认头像
const defaultAvatar = 'https://ts1.tc.mm.bing.net/th/id/OIP-C.zkgnSpOw7PiuiMYOWpGfawHaGL?w=240&h=211&c=8&rs=1&qlt=90&o=6&cb=thwsc5&dpr=2.3&pid=3.1&rm=2'

// 当前用户信息
const currentUser = JSON.parse(localStorage.getItem('admin') || 'null')
const currentUserAvatar = currentUser?.avatar || defaultAvatar

// 帖子相关数据
const post = ref({})
const postImages = ref([])
const currentSwipe = ref(0)

// 互动相关数据
const isLiked = ref(false)
const comments = ref([])
const commentCount = computed(() => comments.value.length)
const newComment = ref('')
const showCommentInput = ref(false)
const replyTo = ref(null) // 用于回复特定评论

// 获取帖子详情
const getPostDetail = async () => {
  try {
    const postId = route.query.id
    if (!postId) {
      console.error('未获取到帖子ID')
      return
    }
    
    const res = await api.postReq(`/post/selectById?id=${postId}`)
    const result = res.data
    
    if (result.code === 1) {
      post.value = result.data
      
      // 处理图片
      if (post.value.images) {
        postImages.value = post.value.images.split(',').filter(img => img.trim())
      }
      
      // 处理评论
      if (post.value.comments && Array.isArray(post.value.comments)) {
        // 为每条评论添加isLiked属性，实际项目中应从接口获取
        comments.value = post.value.comments.map(comment => ({
          ...comment,
          isLiked: false
        }))
      }
      
      // 检查当前用户是否已点赞
      checkUserLikeStatus(postId)
    } else {
      console.error('获取帖子详情失败:', result.msg)
    }
  } catch (error) {
    console.error('获取帖子详情出错:', error)
  }
}

// 检查用户是否已点赞
const checkUserLikeStatus = async (postId) => {
  if (!currentUser?.id) return
  
  try {
    // 实际项目中应调用接口检查用户是否已点赞
    // 这里只是模拟
    api.postReq('/like/selectIsLike',{
      userId:currentUser.id,
      likedType:1,
      likedId:route.query.id
    }).then(res=>{
      let result=res.data
      console.log(result.msg)
      if(result.code==1){
        
        isLiked.value = true
      }else{
        isLiked.value = false
      }
    })
    //  isLiked.value = false
  } catch (error) {
    console.error('检查点赞状态失败:', error)
  }
}

// 页面挂载时获取帖子详情 同时新增浏览量
onMounted(() => {
  getPostDetail()
})

// 返回上一页
const goBack = () => {
  router.back()
}

// 处理图片加载错误
const handleImageError = (e, index) => {
  const img = e.target
  img.src = defaultAvatar
}

// 格式化时间
const formatTime = (timeString) => {
  if (!timeString) return ''
  
  const date = new Date(timeString)
  const now = new Date()
  const diffMs = now - date
  const diffMins = Math.floor(diffMs / (1000 * 60))
  const diffHours = Math.floor(diffMins / 60)
  const diffDays = Math.floor(diffHours / 24)
  
  // 时间差小于1分钟，显示"刚刚"
  if (diffMins < 1) {
    return '刚刚'
  }
  // 时间差小于1小时，显示"X分钟前"
  else if (diffHours < 1) {
    return `${diffMins}分钟前`
  }
  // 时间差小于1天，显示"X小时前"
  else if (diffDays < 1) {
    return `${diffHours}小时前`
  }
  // 时间差小于7天，显示"X天前"
  else if (diffDays < 7) {
    return `${diffDays}天前`
  }
  // 超过7天，显示具体日期
  else {
    return `${date.getFullYear()}-${padZero(date.getMonth() + 1)}-${padZero(date.getDate())}`
  }
}

// 数字补零
const padZero = (num) => {
  return num < 10 ? `0${num}` : num
}

// 点赞处理
const handleLike = async () => {
  if (!currentUser?.id) {
    // 未登录，跳转到登录页
    router.push('/login')
    return
  }
  
  try {
    // 调用点赞接口
    const res = await api.postReq('/post/addLikeCount', {
      userId: currentUser.id,
      likedType: true,
      likedId: post.value.id
    })
    
    const result = res.data
    if (result.code === 1 || result.code === 2) {
      isLiked.value = !isLiked.value
      post.value.likeCount = result.data
    } else {
      console.error('点赞操作失败:', result.msg)
    }
  } catch (error) {
    console.error('点赞请求出错:', error)
  }
}

// 评论点赞
const handleCommentLike = async (comment) => {
  if (!currentUser?.id) {
    router.push('/login')
    return
  }
  
  try {
    // 调用评论点赞接口
    const res = await api.postReq('/comment/addLikeCount', {
      userId: currentUser.id,
      likedType: false,
      likedId: comment.id
    })
    
    const result = res.data
    if (result.code === 1 || result.code === 2) {
      comment.isLiked = !comment.isLiked
      comment.likeCount = result.data
    } else {
      console.error('评论点赞失败:', result.msg)
    }
  } catch (error) {
    console.error('评论点赞请求出错:', error)
  }
}

// 回复评论
const replyToComment = (comment) => {
  replyTo.value = comment
  newComment.value = `@${comment.user?.username} `
  showCommentInput.value = true
  
  // 自动聚焦到输入框（实际项目中可能需要使用ref实现）
  setTimeout(() => {
    const input = document.querySelector('.comment-input')
    if (input) input.focus()
  }, 100)
}

// 添加评论
const addComment = async () => {
  if (!currentUser?.id) {
    router.push('/login')
    return
  }
  
  const content = newComment.value.trim()
  if (!content) return
  
  try {
    // 调用添加评论接口
    const params = {
      userId: currentUser.id,
      targetType: true,
      targetId: post.value.id,
      content: content,
      parentId: replyTo.value?.id || null
    }
    
    const res = await api.postReq('/comment/addComment', params)
    const result = res.data
    
    if (result.code === 1) {
      // 添加成功，更新评论列表
      const newCommentObj = {
        id: result.data, // 假设接口返回新评论ID
        userId: currentUser.id,
        user: {
          username: currentUser.username,
          avatar: currentUser.avatar
        },
        content: content,
        createTime: new Date().toISOString(),
        likeCount: 0,
        isLiked: false,
        parentId: replyTo.value?.id || null
      }
      
      comments.value.unshift(newCommentObj)
      newComment.value = ''
      showCommentInput.value = false
      replyTo.value = null
    } else {
      console.error('添加评论失败:', result.msg)
    }
  } catch (error) {
    console.error('添加评论请求出错:', error)
  }
}
</script>

<style scoped>
.post-detail {
  max-width: 500px;
  margin: 0 auto;
  background-color: #fff;
  min-height: 100vh;
}

/* 用户信息 */
.user-info {
  display: flex;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #f5f5f5;
}

.user-avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  object-fit: cover;
  margin-right: 12px;
}

.user-meta {
  flex: 1;
}

.username {
  font-weight: bold;
  font-size: 16px;
  margin-bottom: 4px;
}

.post-time {
  font-size: 12px;
  color: #999;
}

/* 帖子内容 */
.post-main {
  padding: 15px;
}

.post-title {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 15px;
  line-height: 1.4;
}

.post-text {
  font-size: 16px;
  line-height: 1.6;
  margin-bottom: 15px;
  color: #333;
}

/* 图片轮播 */
.van-swipe {
  width: 100%;
  height: 300px;
}

.swipe-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* 元数据 */
.post-meta {
  padding: 0 15px 15px;
  display: flex;
  gap: 15px;
  font-size: 14px;
  color: #999;
  border-bottom: 1px solid #f5f5f5;
}

.meta-item {
  display: flex;
  align-items: center;
}

/* 互动区域 */
.interaction {
  display: flex;
  justify-content: center;
  gap: 30px;
  padding: 15px 0;
  border-bottom: 1px solid #f5f5f5;
}

.interaction .van-button {
  display: flex;
  align-items: center;
  gap: 5px;
}

.liked {
  color: #ff4d4f !important;
}

/* 评论区域 */
.comments {
  padding: 15px;
}

.comments h4 {
  font-size: 16px;
  margin-bottom: 15px;
  font-weight: bold;
}

.comment-list {
  margin-bottom: 20px;
}

.comment-item {
  display: flex;
  margin-bottom: 15px;
  padding-bottom: 15px;
  border-bottom: 1px solid #f5f5f5;
}

.comment-item:last-child {
  border-bottom: none;
}

.comment-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 10px;
  object-fit: cover;
}

.comment-info {
  flex: 1;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
}

.comment-username {
  font-weight: bold;
  font-size: 14px;
}

.comment-time {
  font-size: 12px;
  color: #999;
}

.comment-content {
  font-size: 15px;
  margin-bottom: 8px;
  line-height: 1.5;
}

.comment-actions {
  display: flex;
  gap: 15px;
}

.like-comment, .reply-comment {
  display: flex;
  align-items: center;
  gap: 3px;
  background: none;
  border: none;
  color: #999;
  font-size: 12px;
  cursor: pointer;
  padding: 2px 5px;
  border-radius: 4px;
}

.like-comment:hover, .reply-comment:hover {
  background-color: #f5f5f5;
}

.like-comment .liked {
  color: #ff4d4f;
}

/* 空评论提示 */
.empty-comments {
  text-align: center;
  padding: 30px 0;
  color: #999;
  font-size: 14px;
  background-color: #f9f9f9;
  border-radius: 8px;
}

/* 评论输入框 */
.comment-input-container {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px 0;
}

.input-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  object-fit: cover;
}

.comment-input {
  flex: 1;
  padding: 10px 12px;
  border: 1px solid #ddd;
  border-radius: 20px;
  outline: none;
  font-size: 14px;
  line-height: 1.4;
}

.comment-input:focus {
  border-color: #1890ff;
}
</style>
